#include "sem.h"

#define SEM_CONTROL_P 0
#define SEM_CONTROL_C 1

int main()
{
    unsigned short values[]={1,0};
    int semid = sem_create(2,values);
    if(semid == -1)
    {
        printf("create sem failed,\n");
        exit(EXIT_FAILURE);
    }
    FILE* fileid  = fopen("log","w+");
    pid_t pid = fork();
    if(pid == -1)
    {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    else if(pid==0)
    {
        char s[128]={0};
        time_t now;
        while(1)
        {
            sem_occupy(SEM_CONTROL_C);
            now = time(NULL);
            // %c: 本地时间
            strftime(s, sizeof s, ".<%Y/%m/%d %X>", localtime(&now));
            fwrite(s,1,strlen(s),fileid);
            fflush(fileid);
            sem_release(SEM_CONTROL_P);
        }
    }
    else
    {
        char count = '0';
        while(1)
        {
            count++;
            if(count > '9')
            {
                break;
            }
            sem_occupy(SEM_CONTROL_P);
            fwrite(&count,1,1,fileid);
            fflush(fileid);
            sem_release(SEM_CONTROL_C);
            
            sem_occupy(SEM_CONTROL_P);
            fwrite("\n",1,2,fileid);
            fflush(fileid);
            sleep(1);
            sem_release(SEM_CONTROL_P);
        }
        kill(pid,SIGKILL);
        wait(NULL);
    }
}
